package com.itc.bpm.framework.quartz;

import com.itc.bpm.bean.BpmProcessInstanceExt;
import com.itc.bpm.bean.BpmProcessTaskExt;
import com.itc.bpm.dto.MessageDto;
import com.itc.bpm.framework.service.TaskExtService;
import com.itc.bpm.framework.websocket.WebSocketServer;
import com.itc.bpm.service.BpmProcessInstanceExtService;
import com.itc.bpm.service.BpmProcessTaskExtService;
import com.itc.bpm.util.JsonUtils;
import com.itc.common.core.utils.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 定时任务信息
 */
@DisallowConcurrentExecution
@Component
public class TaskJob implements Job {

    public static final BpmProcessTaskExtService bpmProcessTaskExtService;
    public static final  DynamicQuartzScheduler dynamicQuartzScheduler;

    public static final WebSocketServer webSocketServer;

    public static final BpmProcessInstanceExtService bpmProcessInstanceExtService;

    static {
         bpmProcessTaskExtService = (BpmProcessTaskExtService) SpringContextJobUtil.getBeanByClass(BpmProcessTaskExtService.class);
         dynamicQuartzScheduler = (DynamicQuartzScheduler) SpringContextJobUtil.getBeanByClass(DynamicQuartzScheduler.class);
         webSocketServer = (WebSocketServer) SpringContextJobUtil.getBeanByClass(WebSocketServer.class);
        bpmProcessInstanceExtService = (BpmProcessInstanceExtService) SpringContextJobUtil.getBeanByClass(BpmProcessInstanceExtService.class);
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getMergedJobDataMap();
        String candidateUsers = null;
        try {
            candidateUsers = dataMap.get("candidateUsers")+"";
            candidateUsers = candidateUsers.replace("[","");
            candidateUsers = candidateUsers.replace("]","");
        }catch (Exception e){
            e.printStackTrace();
        }
        String taskId = dataMap.getString("taskId");
        String taskName = dataMap.getString("taskName");


        Integer noticeType = dataMap.getIntegerFromString("noticeType");
        BpmProcessTaskExt bpmProcessTaskExt = bpmProcessTaskExtService.findTaskByTaskId(taskId);

        BpmProcessInstanceExt bpmProcessInstanceExt = new BpmProcessInstanceExt();
        if(bpmProcessTaskExt!=null){
            bpmProcessInstanceExt = bpmProcessInstanceExtService.getProcessInstanceExtByInstanceId(bpmProcessTaskExt.getProcessInstanceId());
        }
        // 检查任务是否被认领
        if(noticeType==1){
            // 未被认领，发送超时通知消息
            if(bpmProcessTaskExt!=null && bpmProcessTaskExt.getStatus()==0){
                MessageDto messageDto = new MessageDto();
                messageDto.setTaskName(taskName);
                messageDto.setTaskId(taskId);
                messageDto.setType(1);
                messageDto.setDate(LocalDateTime.now());
                messageDto.setProcessInstanceId(bpmProcessTaskExt.getProcessInstanceId());
                messageDto.setProcessInstanceName(bpmProcessInstanceExt.getName());
                messageDto.setModelId(bpmProcessInstanceExt.getBpmModelId()+"");
                try {
                    if(candidateUsers.contains(",")){
                        String[]  users = candidateUsers.split(",");
                        for(String userDept:users){
                            if(StringUtils.isNotEmpty(userDept)){
                                webSocketServer.sendInfo(JsonUtils.objectToJson(messageDto),userDept);
                            }
                        }
                    }else{
                        webSocketServer.sendInfo(JsonUtils.objectToJson(messageDto),candidateUsers);
                    }
                } catch (IOException e) {
                    throw new RuntimeException("socket 消息失败");
                }
            }else{
                dynamicQuartzScheduler.cancelJob(taskId,taskId);
            }
        }else if(noticeType==2){// 检查任务是否被完成
            if(bpmProcessTaskExt!=null && bpmProcessTaskExt.getStatus()==1){
                MessageDto messageDto = new MessageDto();
                messageDto.setTaskName(taskName);
                messageDto.setTaskId(taskId);
                messageDto.setType(3);
                messageDto.setDate(LocalDateTime.now());
                messageDto.setProcessInstanceId(bpmProcessTaskExt.getProcessInstanceId());
                messageDto.setProcessInstanceName(bpmProcessInstanceExt.getName());
                messageDto.setModelId(bpmProcessInstanceExt.getBpmModelId()+"");
                try {
                    webSocketServer.sendInfo(JsonUtils.objectToJson(messageDto),candidateUsers);
                } catch (IOException e) {
                    throw new RuntimeException("socket 消息失败");
                }
            }else{
                String jobName = TaskExtService.TASK_JOB_PREFIX+"_"+taskId;
                dynamicQuartzScheduler.cancelJob(jobName,jobName);
            }
        }else if(noticeType==3){// 检查循环任务是否被完成
            if(bpmProcessTaskExt!=null && bpmProcessTaskExt.getStatus()==1){
                MessageDto messageDto = new MessageDto();
                messageDto.setTaskName(taskName);
                messageDto.setTaskId(taskId);
                messageDto.setType(3);
                messageDto.setDate(LocalDateTime.now());
                messageDto.setProcessInstanceId(bpmProcessTaskExt.getProcessInstanceId());
                messageDto.setProcessInstanceName(bpmProcessInstanceExt.getName());
                messageDto.setModelId(bpmProcessInstanceExt.getBpmModelId()+"");
                try {
                    webSocketServer.sendInfo(JsonUtils.objectToJson(messageDto),candidateUsers);
                } catch (IOException e) {
                    throw new RuntimeException("socket 消息失败");
                }
            }else{
                String jobName = TaskExtService.CIRCULATE_TASK_JOB_PREFIX+"_"+taskId;
                dynamicQuartzScheduler.cancelJob(jobName,jobName);
            }
        }
    }
}
